package com.nginxmanager.controller;

import com.nginxmanager.domain.Conf;
import com.nginxmanager.domain.User;
import com.nginxmanager.server.IUserRepository;
import com.nginxmanager.server.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created by Administrator on 2018-02-24.
 */
@RestController
@RequestMapping("/nginx")
@Api(tags = "用户安全")
@CrossOrigin
public class UserController {


    private IUserService userService;
    private IUserRepository iUserRepository;

    @Autowired
    public UserController(IUserService userService,IUserRepository iUserRepository) {
        this.userService = userService;
        this.iUserRepository = iUserRepository;
    }

    /**
     * 用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
    @ApiOperation("用户登录代码")
    @PostMapping(value = "/login", params = {"username", "password"})
    public String getToken(String username, String password) throws AuthenticationException {
        return userService.login(username, password);
    }

    /**
     * 用户注册
     *
     * @param user          用户信息
     * @return 操作结果
     * @throws AuthenticationException 错误信息
     */
    @ApiOperation("管理员为用户注册")
    @PreAuthorize("hasAuthority('ROLE_ADMIN')")
    @PostMapping(value = "/register")
    public String userRegister(@RequestBody User user) throws AuthenticationException {
        return userService.register(user);
    }
    /**
     * 用户注册
     *
     * @param user          用户信息
     * @return 操作结果
     * @throws AuthenticationException 错误信息管理员账号注册
     */
    @ApiOperation("管理员为用户注册")
    @PostMapping(value = "/adminRegister")
    public String adminRegister(@RequestBody User user) throws AuthenticationException {
        return userService.adminRegister(user);
    }
    /**
     * 刷新密钥
     *
     * @param authorization 原密钥
     * @return 新密钥
     * @throws AuthenticationException 错误信息
     */
    @GetMapping(value = "/refreshToken")
    public String refreshToken(@RequestHeader String authorization) throws AuthenticationException {
        return userService.refreshToken(authorization);
    }

    @GetMapping(value = "/getUserRlose")
    @ApiOperation("查看用户角色信息")
    public ResponseEntity<String> getUserRlose (@RequestParam("username")String username){
        User user = iUserRepository.findUserByUsername(username);
        return ResponseEntity.status(200).body(user.getRoles());
    }
}
